import { FC, useEffect, useRef, useMemo, useState } from 'react';
import dayjs from 'dayjs';
import classNames from 'classnames';
import ReactECharts from 'echarts-for-react';
import { Select } from '@supcon/supcon-5t-design';
import styles from './index.module.less';

// 自定义ECharts系列类型
interface CustomChartSeries {
  name: string;
  data: any[]; // 可以是number[]或[string, number][]
  type: 'line';
  smooth?: boolean;
  symbol?: string;
  symbolSize?: number;
  itemStyle?: {
    color?: string;
    borderColor?: string;
    borderWidth?: number;
  };
  lineStyle?: {
    color?: string;
    width?: number;
    type?: 'solid' | 'dashed' | 'dotted';
  };
  markPoint?: {
    data: {
      name: string;
      coord: any[];
      itemStyle?: {
        color?: string;
        borderColor?: string;
        borderWidth?: number;
      };
    }[];
  };
}

interface TrendData {
  tagName?: string;
  times?: string[];
  values?: string[];
  dashedTime?: string
}

interface ChartPointModalProps {
  visible: boolean;
  title?: string;
  type?: "red" | "yellow" | "green" | "gray";
  chartData?: TrendData | TrendData[];
  codeOptions?: string[];
  onClose: () => void;
}

const ChartPointModal: FC<ChartPointModalProps> = ({
  visible,
  title = '异常数据趋势',
  type = 'green',
  chartData: orgChartData,
  codeOptions = [],
  onClose
}) => {
  const modalRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedCodes, setSelectedCodes] = useState<string[]>([]);
  const [chartData, setChartData] = useState<TrendData | TrendData[]>(orgChartData || []);

  useEffect(() => {
    if (visible && codeOptions.length > 0) {
      setSelectedCodes([...codeOptions]);
      setChartData(orgChartData || []);
    }
  }, [visible, codeOptions]);

  // ! 这边先注释因为 下拉框点击会取消
  // useEffect(() => {
  //   const handleClickOutside = (event: MouseEvent) => {
  //     if (modalRef.current && !modalRef.current.contains(event.target as Node)) {
  //       onClose();
  //     }
  //   };

  //   if (visible) {
  //     document.addEventListener('mousedown', handleClickOutside);
  //   }

  //   return () => {
  //     document.removeEventListener('mousedown', handleClickOutside);
  //   };
  // }, [visible, onClose]);

  const getModalClassName = () => {
    return classNames(
      styles['modal-container'],
      {
        [styles['visible']]: visible,
        [styles['modal-red']]: type === 'red',
        [styles['modal-yellow']]: type === 'yellow',
        [styles['modal-green']]: type === 'green',
      }
    );
  };

  const getChartOptions = useMemo(() => {
    const colorMap = {
      'red': 'rgba(255, 77, 79, 1)',
      'yellow': 'rgba(250, 173, 20, 1)',
      'green': 'rgba(82, 196, 26, 1)',
      'gray': 'rgba(191, 191, 191, 1)',
      'default': 'rgba(3, 251, 255, 1)'
    };

    const mainColor = colorMap[type as keyof typeof colorMap] || colorMap.default;

    if (!chartData) {
      return {
        grid: {
          left: 40,
          right: 20,
          top: 30,
          bottom: 50,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLine: {
            show: true,
            lineStyle: { color: 'rgba(255, 255, 255, 0.3)' }
          },
          axisTick: { show: false },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 10,
          },
        },
        yAxis: {
          type: 'value',
          show: true,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: {
            show: true,
            lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
          },
          axisLabel: {
            show: true,
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 10,
            formatter: (value: number) => value.toFixed(2)
          },
        },
        series: []
      };
    }

    const isMultiLine = Array.isArray(chartData) && chartData.length > 1;

    if (isMultiLine) {
      const allTrendData = chartData as TrendData[];

      const timeMap = new Map<string, string>();

      allTrendData.forEach(trend => {
        if (trend && trend.times) {
          trend.times.forEach(time => {
            const standardTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            timeMap.set(standardTime, time);
          });
        }
      });

      const allTimes = Array.from(timeMap.values()).sort((a, b) =>
        new Date(a).getTime() - new Date(b).getTime()
      );

      const xAxisData = allTimes.map(time => {
        try {
          return dayjs(time).format('HH:mm');
        } catch (err) {
          return time;
        }
      });

      const orgSeries = allTrendData.map((trend, index) => {
        if (!trend || !trend.values || !trend.times) return null;

        const trendValues = trend.values || [];
        const trendTimes = trend.times || [];

        if (trend.dashedTime) {
          // 区分 实线和虚线
          let dashedTime = new Date(trend.dashedTime).getTime();
          let trend1Times: any = [];
          let trend2Times: any = []
          trendTimes.forEach((time, timeIdx) => {
            const idx = allTimes.findIndex(t =>
              dayjs(t).format('YYYY-MM-DD HH:mm:ss') === dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            );

            if (idx >= 0 && timeIdx < trendValues.length) {
              if (new Date(time).getTime() < dashedTime) {
                trend1Times.push(time);
                trend2Times.push('-')
              } else {
                trend2Times.push(time)
              }
            }
          })
          let lenTrend1Times = trend1Times.length;
          if (lenTrend1Times) {
            // 这边是处理实线和虚线交接
            trend2Times[lenTrend1Times - 1] = trend1Times[lenTrend1Times - 1];
          }

          const data1Points = trend1Times.map((time, timeIdx) => {
            const idx = allTimes.findIndex(t =>
              dayjs(t).format('YYYY-MM-DD HH:mm:ss') === dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            );

            if (idx >= 0 && time !== '-' && timeIdx < trendValues.length) {
              return [xAxisData[idx], parseFloat(trendValues[timeIdx])];
            }
            return '-';
          })
          const data2Points = trend2Times.map((time, timeIdx) => {
            const idx = allTimes.findIndex(t =>
              dayjs(t).format('YYYY-MM-DD HH:mm:ss') === dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            );

            if (idx >= 0 && timeIdx < trendValues.length) {
              return [xAxisData[idx], parseFloat(trendValues[timeIdx])];
            }
            return '-';
          })
          const colorArray = [
            mainColor,
            'rgba(255, 145, 0, 1)',
            'rgba(0, 208, 132, 1)',
            'rgba(51, 133, 255, 1)',
            'rgba(245, 34, 45, 1)'
          ];
          let s1 = {

          } as CustomChartSeries;
          let s2 = {

          } as CustomChartSeries;
          if (trend1Times.length) {
            s1 = {
              name: trend.tagName || `数据${index + 1}`,
              data: data1Points,
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              itemStyle: {
                color: '#fff',
                borderColor: colorArray[index % colorArray.length],
                borderWidth: 1,
              },
              lineStyle: {
                color: colorArray[index % colorArray.length],
                width: 2,
              }
            } as CustomChartSeries
          }
          if (trend2Times.length) {
            s2 = {
              name: trend.tagName || `数据${index + 1}`,
              data: data2Points,
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              itemStyle: {
                color: '#fff',
                borderColor: colorArray[index % colorArray.length],
                borderWidth: 1,
              },
              lineStyle: {
                color: colorArray[index % colorArray.length],
                width: 2,
                type: 'dashed'
              }
            } as CustomChartSeries;
          }
          return [s1, s2]

        } else {
          // 全是 实线
          const dataPoints = trendTimes.map((time, timeIdx) => {
            const idx = allTimes.findIndex(t =>
              dayjs(t).format('YYYY-MM-DD HH:mm:ss') === dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            );

            if (idx >= 0 && timeIdx < trendValues.length) {
              return [xAxisData[idx], parseFloat(trendValues[timeIdx])];
            }
            return null;
          }).filter(point => point !== null);

          const colorArray = [
            mainColor,
            'rgba(255, 145, 0, 1)',
            'rgba(0, 208, 132, 1)',
            'rgba(51, 133, 255, 1)',
            'rgba(245, 34, 45, 1)'
          ];

          return {
            name: trend.tagName || `数据${index + 1}`,
            data: dataPoints,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#fff',
              borderColor: colorArray[index % colorArray.length],
              borderWidth: 1,
            },
            lineStyle: {
              color: colorArray[index % colorArray.length],
              width: 2,
            }
          } as CustomChartSeries;
        }

      }).filter(Boolean) as CustomChartSeries[];
      let series = orgSeries.flat(Infinity).filter((item) => item.name);

      return {
        grid: {
          left: 40,
          right: 20,
          top: 30,
          bottom: 50,
          containLabel: true

        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
            xAxisIndex: 0,
            filterMode: 'filter',
            zoomOnMouseWheel: true,
            moveOnMouseMove: true
          }
        ],
        legend: {
          data: series.map(item => item.name),
          top: 5,
          left: 'center',
          orient: 'horizontal',
          textStyle: {
            color: 'rgba(255, 255, 255, 0.8)',
            fontSize: 12,
          },
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 10,
          icon: 'rect',
          type: 'scroll',
          pageIconColor: '#aaa', // 翻页按钮的颜色
          pageIconInactiveColor: '#2f4554', // 翻页按钮不激活时（即翻页到头时）的颜色
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params: any) {
            let result = params[0].axisValue;
            params.forEach((param: any) => {
              if (param.value !== null && param.value !== '-' && !result.includes(param.seriesName)) {
                let num = parseFloat(param?.value?.[1]);
                let cValue = !isNaN(num) ? num.toFixed(2) : '暂无数据';
                result += `<br />${param.seriesName}: ${cValue}`;
              }
            });
            return result;
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: {
            show: true,
            lineStyle: { color: 'rgba(255, 255, 255, 0.3)' }
          },
          axisTick: { show: false },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 10,
            rotate: 45,
          },
        },
        yAxis: {
          type: 'value',
          show: true,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: {
            show: true,
            lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
          },
          axisLabel: {
            show: true,
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 10,
            formatter: (value: number) => value.toFixed(2)
          },
          min: (value: any) => Math.floor(value.min) * 0.9,
          max: (value: any) => Math.ceil(value.max) * 1.1,
        },
        series: [...series],
      };
    } else {
      const singleTrendData = Array.isArray(chartData) && chartData.length > 0
        ? chartData[0]
        : chartData as TrendData;

      if (!singleTrendData || !singleTrendData.times || !singleTrendData.values) {
        return {};
      }

      const xAxisData = singleTrendData.times.map((time: string) => {
        try {
          return dayjs(time).format('HH:mm');
        } catch (err) {
          return time;
        }
      });

      let orgSeries: any = [];
      if (singleTrendData.dashedTime) {
        // 区分 实线和虚线
        let dashedTime = new Date(singleTrendData.dashedTime).getTime();
        let trend1Times: any = [];
        let trend2Times: any = [];
        singleTrendData?.times?.forEach((time) => {
          if (new Date(time).getTime() < dashedTime) {
            trend1Times.push(time);
            trend2Times.push('-')
          } else {
            trend2Times.push(time)
          }
        });
        let lenTrend1Times = trend1Times.length;
        if (lenTrend1Times) {
          // 这边是处理实线和虚线交接
          trend2Times[lenTrend1Times - 1] = trend1Times[lenTrend1Times - 1];
        }
        let s1 = {

        } as CustomChartSeries;
        let s2 = {

        } as CustomChartSeries;
        if (trend1Times.length) {

          s1 = {
            name: singleTrendData?.tagName ?? '实际值',
            data: trend1Times.map((value: string, index: number) => [xAxisData[index], parseFloat(singleTrendData?.values?.[index] as any)]),
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#fff',
              borderColor: mainColor,
              borderWidth: 1
            },
            lineStyle: {
              color: mainColor,
              width: 2,
            }
          } as CustomChartSeries
        }
        if (trend2Times.length) {
          let dataPoint = trend2Times.map((value: string, index: number) => {
            if (value !== '-') {
              return [xAxisData[index], parseFloat(singleTrendData?.values?.[index] as any)]
            }
            return '-'
          })
          s2 = {
            name: singleTrendData?.tagName ?? '实际值',
            data: dataPoint,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#fff',
              borderColor: mainColor,
              borderWidth: 1
            },
            lineStyle: {
              color: mainColor,
              width: 2,
              type: 'dashed'
            }
          } as CustomChartSeries;
        }
        orgSeries = [s1, s2];

      } else {
        orgSeries = [{
          name: singleTrendData?.tagName ?? '实际值',
          data: singleTrendData.values.map((value: string, index: number) => [xAxisData[index], parseFloat(value)]),
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#fff',
            borderColor: mainColor,
            borderWidth: 1
          },
          lineStyle: {
            color: mainColor,
            width: 2,
          }
        } as CustomChartSeries];
      }
      let series = orgSeries.flat(Infinity).filter((item) => item.name);
      return {
        grid: {
          left: 40,
          right: 20,
          top: 30,
          bottom: 50,
          containLabel: true
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
            xAxisIndex: 0,
            filterMode: 'filter',
            zoomOnMouseWheel: true,
            moveOnMouseMove: true
          }
        ],
        legend: {
          data: series.map(item => item.name),
          top: 5,
          left: 'center',
          textStyle: {
            color: 'rgba(255, 255, 255, 0.8)',
            fontSize: 12,
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params: any) {
            let result = params[0].axisValue;
            params.forEach((param: any) => {
              if (param.value !== null && param.value !== '-' && !result.includes(param.seriesName)) {
                let num = parseFloat(param?.value?.[1]);
                let cValue = !isNaN(num) ? num.toFixed(2) : '暂无数据';
                result += `<br />${param.seriesName}: ${cValue}`;
              }
            });
            return result;
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: {
            show: true,
            lineStyle: { color: 'rgba(255, 255, 255, 0.3)' }
          },
          axisTick: { show: false },
          axisLabel: {
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 10,
            rotate: 45,
          },
        },
        yAxis: {
          type: 'value',
          show: true,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: {
            show: true,
            lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
          },
          axisLabel: {
            show: true,
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: 10,
            formatter: (value: number) => value.toFixed(2)
          },
          min: (value: any) => Math.floor(value.min) * 0.9,
          max: (value: any) => Math.ceil(value.max) * 1.1,
        },
        series: [...series],
      };
    }
  }, [chartData, type]);

  const handleSelectChange = (value: string[]) => {
    setLoading(true)
    setSelectedCodes(value);
    console.log('选中的code:', value);
    if (Array.isArray(orgChartData)) {
      if (!value.length) {
        setChartData([]);
      } else {
        let currentChartData = orgChartData.map((item: any) => {
          if (value.includes(item?.tagName)) {
            return item
          } else {
            return null
          }
        }).filter((item) => item);

        setChartData(currentChartData || []);
      }

    }
    setLoading(false)
  };

  if (!visible) return null;

  return (
    <>
      <div className={styles['modal-overlay']} onClick={onClose} />

      <div
        className={getModalClassName()}
        ref={modalRef}
      >
        <div className={styles['modal-header']}>
          <div className={styles['modal-title']}>{title}</div>
          <button className={styles['close-btn']} onClick={onClose}>×</button>
        </div>

        <div className={styles['modal-content']}>
          {codeOptions.length > 0 && (
            <div className={styles['select-container']}>
              <Select
                mode="multiple"
                placeholder="请选择要显示的编码"
                value={selectedCodes}
                onChange={handleSelectChange}
                style={{
                  width: '90%',
                  background: 'transparent',
                  color: '#fff'
                }}
                options={codeOptions.map(code => ({ label: code, value: code }))}
                maxTagCount={3}
                maxTagTextLength={8}
              // allowClear
              />
            </div>
          )}

          <div className={styles['chart-container']}>
            <ReactECharts
              key={Date.now()}
              option={getChartOptions}
              style={{ height: '100%', width: '100%' }}
              opts={{ renderer: 'canvas' }}
              showLoading={loading}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default ChartPointModal;